<script setup>
	import {getCurrentInstance, onBeforeUnmount, onMounted, ref} from "vue";
	import {getToken} from "@/utils/auth";
	import {addArticle, getArticleByKey, updArticle} from "@/api/article/manage";
	import Editor from '@/components/RichText/index.vue'
	const { proxy } = getCurrentInstance();
	import emitter from "@/utils/mitt";
	
	const props = defineProps({
		rowId: {
			type: [Number, String],
			default: null
		},
		articleColumn: {
			type: Array,
			default: []
		}
	})
	
	// const elForm = ref(null);
	const formData = ref({
		// 文章栏目id
		articleColumnId: null,
		// 文章内容
		content: '',
		// 文章表-主键id
		id: null,
		// 是否滚动
		isRoll: 0,
		// 是否置顶
		isTop: 0,
		// 是否展示
		isView: 1,
		// 概要
		outline: '',
		// 富文本文件
		richFileIds: [],
		// 文章标题
		title: '',
		// 标题图片
		titleFileIds: [],
	});
	const rules = ref({
		title: [{required: true, message: '请输入文章标题', trigger: 'blur'}],
	});
	
	const fileRichAction = import.meta.env.VITE_APP_BASE_API + "/article/addRichFile"
	const fileTitleAction = import.meta.env.VITE_APP_BASE_API + "/article/addTitleImg"
	
	const isFirstPic = ref(false)
	const titleFilesData = ref([])
	const richFilesData = ref([])
	
	const removeFirstPic = () => {
		formData.value.titleFileIds = []
		titleFilesData.value = []
		isFirstPic.value = false
	}
	const uploadFirstPic = (response, file, fileList) => {
		if(response.code === 200) {
			formData.value.titleFileIds = [response.data.id]
			titleFilesData.value = [response.data]
		}
	}
	const clearFirstPic = () => {
		formData.value.titleFileIds = []
		titleFilesData.value = []
	}
	
	const getFormData = () => {
		const tempElement = document.createElement('div')
		formData.value.content = proxy.$refs["editorRef"].getCurrentValue()
		console.log('formData.value', formData.value);
		tempElement.innerHTML = formData.value.content
		const imgElements = tempElement.querySelectorAll('img')
		formData.value.richFileIds = [];
		if(imgElements.length > 0) {
			imgElements.forEach(item => {
				let itemTemp = richFilesData.value.find(file => file.accessUrl === item.currentSrc)
				formData.value.richFileIds.push(itemTemp.id)
			});
		}
		return formData.value
	}
	
	const getData = async () => {
		const res = await getArticleByKey({id: props.rowId})
		try {
			if(res.code === 200) {
				const {articleColumnId, content, id, isRoll, isTop, isView, outline, richFiles, title, titleFiles} = res.data
				formData.value.articleColumnId = articleColumnId
				isFirstPic.value = titleFiles.length > 0
				titleFilesData.value = titleFiles
				richFilesData.value = richFiles
				formData.value.content = content
				formData.value.id = id
				formData.value.isRoll = isRoll
				formData.value.isTop = isTop
				formData.value.isView = isView
				formData.value.outline = outline
				formData.value.title = title
				formData.value.titleFileIds = titleFiles.map(item => item.id)
				formData.value.richFileIds = richFiles.map(item => item.id)
				
			}
		}
		catch(e) {
			console.log(e);
		}
	}
	
	const submit = () => {
		proxy.$refs.elForm.validate(async valid => {
			if(valid) {
				const params = getFormData()
				if(params.title == null || params.title === '') return
				if(!params.isFirstPic) params.titleFileIds = []
				delete params.isFirstPic
				let res
				params.id !== null && params !== '' ? res = await updArticle(params) : res = await addArticle(params)
				try {
					if(res.code === 200) {
						proxy.$modal.msgSuccess('操作成功')
						cancel(true)
					}
					else {
						proxy.$modal.msgError(res.msg)
					}
				}
				catch(e) {
					console.log(e);
					proxy.$modal.msgError(JSON.stringify(e))
				}
			}
		})
	}
	
	const cancel = (ifSubmit = false) => {
		emitter.emit('closeEdit', ifSubmit)
	}
	
	onMounted(() => {
		formData.value.articleColumnId = props.articleColumn[0].id
		if(props.rowId) {
			getData();
		}
		emitter.on('richTestFileList', (data) => {
			richFilesData.value = [...richFilesData.value, ...data]
			console.log(richFilesData.value);
		})
	})
	
	onBeforeUnmount(() => {
		emitter.off('richTestFileList')
	})
	
</script>

<template>
	<div class="dialogContent">
		<el-form
			ref="elForm"
			:model="formData"
			:rules="rules"
			label-width="80px"
			style="width: calc(100% - 20px)"
		>
			<el-form-item label="文章标题" prop="title" required>
				<el-input
					v-model="formData.title"
					clearable
					placeholder="请输入文章标题"
				></el-input>
			</el-form-item>
			<el-form-item label="文章概述" prop="outline">
				<el-input
					v-model="formData.outline"
					:autosize="{
						minRows: 3,
					}"
					class="textAreaEdit"
					clearable
					placeholder="请输入文章概述"
					type="textarea"
				></el-input>
			</el-form-item>
			<el-form-item label="文章栏目" prop="articleColumnId">
				<el-select v-model="formData.articleColumnId" placeholder="请选择文章栏目">
					<el-option v-for="item in articleColumn" :key="item.id" :label="item.name" :value="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="设置封面">
				<el-switch v-model="isFirstPic" active-text="是" inactive-text="否"></el-switch>
			</el-form-item>
			<el-form-item v-if="isFirstPic" label="文章封面">
				<el-upload
					ref="uploadFirstPicRef"
					:accept="'.jpg,.jpeg,.png'"
					:action="fileTitleAction"
					:headers="{
						Authorization: 'Bearer ' + getToken()
					}"
					:limit="1"
					:on-remove="removeFirstPic"
					:on-success="uploadFirstPic"
					:show-file-list="false"
				>
					<el-button size="small" type="primary">点击上传</el-button>
					<el-button size="small" type="warning" @click.stop="clearFirstPic">清空上传</el-button>
				</el-upload>
			</el-form-item>
			<el-form-item v-if="isFirstPic && titleFilesData.length > 0" prop="titleFileIds">
				<el-image
					:preview-src-list="[titleFilesData[0].accessUrl]"
					:src="titleFilesData[0].accessUrl"
					style="width: 100px; height: 100px"
				>
				</el-image>
			</el-form-item>
			<el-form-item label="文章内容" prop="content">
				<Editor
					v-model="formData.content"
					:value="formData.content"
					:file-size="20"
					:max-height="500"
					:min-height="130"
					:url="'/article/addRichFile'"
					style="width: 100%"
					ref="editorRef"
				/>
			</el-form-item>
			<el-form-item label="是否展示" prop="isView">
				<el-switch v-model="formData.isView" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
			</el-form-item>
			<el-form-item label="是否置顶" prop="isTop">
				<el-switch v-model="formData.isTop" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
			</el-form-item>
			<el-form-item label="是否滚动" prop="isRoll">
				<el-switch v-model="formData.isRoll" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
			</el-form-item>
		</el-form>
		<div class="buttonList">
			<el-button class="button" type="primary" @click="submit">提交</el-button>
			<el-button class="button" @click="cancel">取消</el-button>
		</div>
	</div>
</template>

<style lang="scss" scoped>
	.dialogContent {
		overflow: auto;
	}
	.buttonList {
		display: flex;
		justify-content: center;
		margin-top: 20px;
	}
</style>
